<template>
  <view class="container">
    <view class="header">
      <text class="title">震动功能测试</text>
    </view>

    <view class="test-section">
      <text class="section-title">权限检查</text>
      <view class="test-item">
        <button class="test-btn" @click="checkPermission">检查震动权限</button>
      </view>
      <view class="test-item">
        <button class="test-btn" @click="requestPermission">
          请求震动权限
        </button>
      </view>
    </view>

    <view class="test-section">
      <text class="section-title">震动API测试</text>
      <view class="test-item">
        <button class="test-btn primary" @click="testUniVibrate">
          测试 uni.vibrate
        </button>
      </view>
      <view class="test-item">
        <button class="test-btn primary" @click="testUniVibrateLong">
          测试 uni.vibrateLong
        </button>
      </view>
      <view class="test-item">
        <button class="test-btn primary" @click="testNativeVibrate">
          测试原生震动
        </button>
      </view>
      <view class="test-item">
        <button class="test-btn primary" @click="testH5Vibrate">
          H5震动详细测试
        </button>
      </view>
      <view class="test-item">
        <button class="test-btn primary" @click="runFullDiagnostic">
          🔍 完整诊断测试
        </button>
      </view>
    </view>

    <view class="test-section">
      <text class="section-title">🚀 快速修复</text>
      <view class="test-item">
        <button class="test-btn fix" @click="oneClickFix">
          🔧 一键修复震动问题
        </button>
      </view>
      <view class="test-item">
        <button class="test-btn fix" @click="forceVibrate">
          ⚡ 强制震动测试
        </button>
      </view>
    </view>

    <view class="test-section">
      <text class="section-title">综合测试</text>
      <view class="test-item">
        <button class="test-btn success" @click="testAllMethods">
          测试所有方法
        </button>
      </view>
      <view class="test-item">
        <button class="test-btn success" @click="powerVibrate">强力震动</button>
      </view>
      <view class="test-item">
        <button class="test-btn success" @click="continuousVibrate">
          连续震动(5次)
        </button>
      </view>
    </view>

    <view class="log-section">
      <text class="section-title">测试日志</text>
      <scroll-view class="log-container" scroll-y>
        <view class="log-item" v-for="(log, index) in logs" :key="index">
          <text class="log-text" :class="log.type">{{ log.message }}</text>
          <text class="log-time">{{ log.time }}</text>
        </view>
      </scroll-view>
      <button class="clear-btn" @click="clearLogs">清空日志</button>
    </view>
  </view>
</template>

<script>
import NativeVibrate from "@/utils/nativeVibrate.js";
import VibrateDebug from "@/utils/vibrateDebug.js";
import VibrateTest from "@/utils/vibrateTest.js";
import VibrateFix from "@/utils/vibrateFix.js";

export default {
  data() {
    return {
      logs: [],
    };
  },
  onLoad() {
    this.addLog("页面加载完成", "info");
    this.detectEnvironment();
  },
  methods: {
    addLog(message, type = "info") {
      const now = new Date();
      const time = `${now.getHours().toString().padStart(2, "0")}:${now
        .getMinutes()
        .toString()
        .padStart(2, "0")}:${now.getSeconds().toString().padStart(2, "0")}`;

      this.logs.unshift({
        message,
        type,
        time,
      });

      // 限制日志数量
      if (this.logs.length > 50) {
        this.logs = this.logs.slice(0, 50);
      }
    },

    checkPermission() {
      this.addLog("检查震动权限...", "info");

      // #ifdef H5
      if (navigator.vibrate) {
        this.addLog("✅ H5环境支持震动API", "success");
      } else {
        this.addLog("❌ H5环境不支持震动API", "error");
        this.addLog("ℹ️ 请在支持震动的设备上测试（如手机浏览器）", "info");
      }
      // #endif

      // #ifndef H5
      const hasPermission = NativeVibrate.checkVibratePermission();
      this.addLog(
        `震动权限状态: ${hasPermission ? "已授予" : "未授予"}`,
        hasPermission ? "success" : "error"
      );
      // #endif
    },

    requestPermission() {
      this.addLog("请求震动权限...", "info");
      NativeVibrate.requestVibratePermission();
    },

    testUniVibrate() {
      this.addLog("测试 uni.vibrate...", "info");

      // #ifdef H5
      // H5环境下模拟震动测试
      if (navigator.vibrate) {
        try {
          navigator.vibrate(200);
          this.addLog("✅ H5 navigator.vibrate 成功", "success");
        } catch (error) {
          this.addLog(
            `❌ H5 navigator.vibrate 失败: ${error.message}`,
            "error"
          );
        }
      } else {
        this.addLog("❌ H5环境不支持震动API", "error");
      }
      // #endif

      // #ifndef H5
      uni.vibrate({
        success: () => {
          this.addLog("✅ uni.vibrate 成功", "success");
        },
        fail: (err) => {
          this.addLog(`❌ uni.vibrate 失败: ${JSON.stringify(err)}`, "error");
        },
      });
      // #endif
    },

    testUniVibrateLong() {
      this.addLog("测试 uni.vibrateLong...", "info");
      try {
        uni.vibrateLong({
          success: () => {
            this.addLog("✅ uni.vibrateLong 成功", "success");
          },
          fail: (err) => {
            this.addLog(
              `❌ uni.vibrateLong 失败: ${JSON.stringify(err)}`,
              "error"
            );
          },
        });
      } catch (error) {
        this.addLog(`❌ uni.vibrateLong 异常: ${error.message}`, "error");
      }
    },

    testNativeVibrate() {
      this.addLog("测试原生震动...", "info");

      // #ifdef APP-PLUS
      try {
        const main = plus.android.runtimeMainActivity();
        const Context = plus.android.importClass("android.content.Context");
        const Vibrator = plus.android.importClass("android.os.Vibrator");

        const vibrator = main.getSystemService(Context.VIBRATOR_SERVICE);

        if (vibrator.hasVibrator()) {
          this.addLog("设备支持震动", "info");

          if (
            plus.android.importClass("android.os.Build$VERSION").SDK_INT >= 26
          ) {
            const VibrationEffect = plus.android.importClass(
              "android.os.VibrationEffect"
            );
            const effect = VibrationEffect.createOneShot(
              1000,
              VibrationEffect.DEFAULT_AMPLITUDE
            );
            vibrator.vibrate(effect);
            this.addLog("✅ 原生震动(新API)执行成功", "success");
          } else {
            vibrator.vibrate(1000);
            this.addLog("✅ 原生震动(旧API)执行成功", "success");
          }
        } else {
          this.addLog("❌ 设备不支持震动", "error");
        }
      } catch (error) {
        this.addLog(`❌ 原生震动失败: ${error.message}`, "error");
      }
      // #endif

      // #ifndef APP-PLUS
      this.addLog("❌ 非APP环境，无法测试原生震动", "error");
      // #endif
    },

    testAllMethods() {
      this.addLog("=== 开始全面测试 ===", "info");
      NativeVibrate.testVibrate();
    },

    powerVibrate() {
      this.addLog("执行强力震动...", "info");
      NativeVibrate.powerVibrate();
    },

    continuousVibrate() {
      this.addLog("执行连续震动(5次)...", "info");
      NativeVibrate.continuousVibrate(5, 800);
    },

    clearLogs() {
      this.logs = [];
      this.addLog("日志已清空", "info");
    },

    // 一键修复震动问题
    async oneClickFix() {
      this.addLog("🚀 开始一键修复震动问题...", "info");
      
      try {
        const report = await VibrateFix.oneClickFix();
        
        // 显示修复结果
        this.addLog(`权限状态: ${report.permissions ? '✅ 正常' : '❌ 异常'}`, 
                   report.permissions ? 'success' : 'error');
        
        report.vibrationTest.forEach(result => {
          const isSuccess = result.includes('成功');
          this.addLog(`震动测试: ${result}`, isSuccess ? 'success' : 'error');
        });
        
        if (report.suggestions.length > 0) {
          this.addLog("💡 修复建议:", "info");
          report.suggestions.forEach(suggestion => {
            this.addLog(`- ${suggestion}`, "info");
          });
        }
        
        if (report.success) {
          this.addLog("🎉 震动功能修复成功！", "success");
        } else {
          this.addLog("⚠️ 震动功能仍有问题，请查看建议", "error");
        }
        
      } catch (error) {
        this.addLog(`❌ 修复过程出错: ${error.message}`, "error");
      }
    },

    // 强制震动测试
    async forceVibrate() {
      this.addLog("⚡ 开始强制震动测试...", "info");
      
      try {
        const results = await VibrateFix.forceVibrate(600);
        
        results.forEach(result => {
          const isSuccess = result.includes('成功');
          this.addLog(`强制测试: ${result}`, isSuccess ? 'success' : 'error');
        });
        
        const hasSuccess = results.some(result => result.includes('成功'));
        if (hasSuccess) {
          this.addLog("✅ 至少一种震动方法有效", "success");
        } else {
          this.addLog("❌ 所有震动方法都失败", "error");
        }
        
      } catch (error) {
        this.addLog(`❌ 强制震动测试失败: ${error.message}`, "error");
      }
    },

    detectEnvironment() {
      this.addLog("=== 环境检测 ===", "info");

      // 检测运行环境
      // #ifdef H5
      this.addLog("当前环境: H5 (浏览器)", "info");
      this.addLog(`User Agent: ${navigator.userAgent}`, "info");

      // 检测设备类型
      const isMobile =
        /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(
          navigator.userAgent
        );
      this.addLog(
        `设备类型: ${isMobile ? "移动设备" : "桌面设备"}`,
        isMobile ? "success" : "info"
      );

      // 检测震动API支持
      if ("vibrate" in navigator) {
        this.addLog("✅ 浏览器支持 navigator.vibrate", "success");

        // 测试震动权限
        try {
          // 尝试短震动测试
          const result = navigator.vibrate(1);
          this.addLog(
            `震动API调用结果: ${result}`,
            result ? "success" : "error"
          );
        } catch (error) {
          this.addLog(`震动API调用异常: ${error.message}`, "error");
        }
      } else {
        this.addLog("❌ 浏览器不支持 navigator.vibrate", "error");
      }

      // 检测HTTPS
      if (location.protocol === "https:") {
        this.addLog("✅ 使用HTTPS协议", "success");
      } else {
        this.addLog("⚠️ 使用HTTP协议，某些API可能受限", "info");
      }

      // 检测权限API
      if ("permissions" in navigator) {
        this.addLog("✅ 浏览器支持权限API", "success");
      } else {
        this.addLog("❌ 浏览器不支持权限API", "error");
      }

      // #endif

      // #ifdef APP-PLUS
      this.addLog("当前环境: APP-PLUS (原生应用)", "info");
      // #endif

      // #ifdef MP-WEIXIN
      this.addLog("当前环境: 微信小程序", "info");
      // #endif
    },

    // 运行完整诊断
    async runFullDiagnostic() {
      this.addLog("🔍 开始完整诊断...", "info");
      
      try {
        const diagnosticLogs = await VibrateTest.getFullDiagnostic();
        
        // 将诊断日志添加到页面日志中
        diagnosticLogs.forEach(log => {
          this.addLog(log.message, log.type);
        });
        
        this.addLog("✅ 完整诊断完成", "success");
        
        // 显示诊断建议
        this.showDiagnosticSuggestions(diagnosticLogs);
        
      } catch (error) {
        this.addLog(`❌ 诊断过程出错: ${error.message}`, "error");
      }
    },

    // 显示诊断建议
    showDiagnosticSuggestions(logs) {
      const errorLogs = logs.filter(log => log.type === 'error');
      const successLogs = logs.filter(log => log.type === 'success');
      
      if (errorLogs.length === 0 && successLogs.length > 0) {
        this.addLog("🎉 震动功能正常！", "success");
      } else if (errorLogs.length > 0) {
        this.addLog("⚠️ 发现问题，请检查以下建议：", "info");
        
        // 权限问题
        if (errorLogs.some(log => log.message.includes('权限'))) {
          this.addLog("💡 建议1: 检查应用权限设置", "info");
        }
        
        // 设备不支持
        if (errorLogs.some(log => log.message.includes('不支持震动'))) {
          this.addLog("💡 建议2: 设备可能不支持震动功能", "info");
        }
        
        // API失败
        if (errorLogs.some(log => log.message.includes('uni.vibrate'))) {
          this.addLog("💡 建议3: 尝试在设置中开启触觉反馈", "info");
          this.addLog("💡 建议4: 检查手机是否开启静音模式", "info");
        }
      }
    },

    // 增强的H5震动测试
    testH5Vibrate() {
      this.addLog("=== H5震动详细测试 ===", "info");

      if (!("vibrate" in navigator)) {
        this.addLog("❌ 浏览器不支持震动API", "error");
        return;
      }

      // 测试1: 基础震动
      this.addLog("测试1: 基础震动 200ms", "info");
      try {
        const result1 = navigator.vibrate(200);
        this.addLog(`基础震动结果: ${result1}`, result1 ? "success" : "error");
      } catch (error) {
        this.addLog(`基础震动异常: ${error.message}`, "error");
      }

      // 测试2: 长震动
      setTimeout(() => {
        this.addLog("测试2: 长震动 1000ms", "info");
        try {
          const result2 = navigator.vibrate(1000);
          this.addLog(`长震动结果: ${result2}`, result2 ? "success" : "error");
        } catch (error) {
          this.addLog(`长震动异常: ${error.message}`, "error");
        }
      }, 1500);

      // 测试3: 震动模式
      setTimeout(() => {
        this.addLog("测试3: 震动模式 [200,100,200,100,200]", "info");
        try {
          const result3 = navigator.vibrate([200, 100, 200, 100, 200]);
          this.addLog(
            `震动模式结果: ${result3}`,
            result3 ? "success" : "error"
          );
        } catch (error) {
          this.addLog(`震动模式异常: ${error.message}`, "error");
        }
      }, 3000);

      // 测试4: 停止震动
      setTimeout(() => {
        this.addLog("测试4: 停止震动", "info");
        try {
          const result4 = navigator.vibrate(0);
          this.addLog(
            `停止震动结果: ${result4}`,
            result4 ? "success" : "error"
          );
        } catch (error) {
          this.addLog(`停止震动异常: ${error.message}`, "error");
        }
      }, 4500);
    },
  },
};
</script>

<style scoped>
.container {
  padding: 30rpx;
  background-color: #f5f5f5;
  min-height: 100vh;
}

.header {
  text-align: center;
  margin-bottom: 40rpx;
}

.title {
  font-size: 40rpx;
  font-weight: 600;
  color: #333;
}

.test-section {
  background-color: #fff;
  border-radius: 20rpx;
  padding: 30rpx;
  margin-bottom: 30rpx;
}

.section-title {
  display: block;
  font-size: 32rpx;
  font-weight: 600;
  color: #333;
  margin-bottom: 20rpx;
}

.test-item {
  margin-bottom: 20rpx;
}

.test-btn {
  width: 100%;
  padding: 25rpx;
  border-radius: 10rpx;
  font-size: 28rpx;
  background-color: #f8f9fa;
  color: #333;
  border: 2rpx solid #e9ecef;
}

.test-btn.primary {
  background-color: #007aff;
  color: #fff;
  border-color: #007aff;
}

.test-btn.success {
  background-color: #28a745;
  color: #fff;
  border-color: #28a745;
}

.test-btn.fix {
  background-color: #ff6b35;
  color: #fff;
  border-color: #ff6b35;
  font-weight: 600;
}

.log-section {
  background-color: #fff;
  border-radius: 20rpx;
  padding: 30rpx;
}

.log-container {
  height: 400rpx;
  border: 2rpx solid #e9ecef;
  border-radius: 10rpx;
  padding: 20rpx;
  margin-bottom: 20rpx;
}

.log-item {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-bottom: 15rpx;
  padding-bottom: 10rpx;
  border-bottom: 1rpx solid #f0f0f0;
}

.log-text {
  flex: 1;
  font-size: 24rpx;
  line-height: 1.4;
  margin-right: 20rpx;
}

.log-text.info {
  color: #333;
}

.log-text.success {
  color: #28a745;
}

.log-text.error {
  color: #dc3545;
}

.log-time {
  font-size: 20rpx;
  color: #999;
  white-space: nowrap;
}

.clear-btn {
  width: 100%;
  padding: 20rpx;
  background-color: #6c757d;
  color: #fff;
  border-radius: 10rpx;
  font-size: 26rpx;
}
</style>
